import { registerAs } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';

/**
 * 支付配置
 * 安全处理敏感信息，仅在运行时从证书文件读取
 */
export default registerAs('payment', () => {
  const isDev =
    process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'development';

  // --- 阿里支付配置 ---
  const alipayConfig = {
    // 应用ID
    appId: process.env.ALIPAY_APP_ID || '2021005145697672',

    // 证书读取
    privateKey: (() => {
      try {
        const certDir = path.join(process.cwd(), 'certs/alipay');
        return fs.readFileSync(path.join(certDir, 'privatekey.pem'), 'ascii');
      } catch (error) {
        console.error('读取支付宝私钥失败:', error.message);
        return process.env.ALIPAY_PRIVATE_KEY || '';
      }
    })(),

    // 支付宝公钥
    alipayPublicKey: (() => {
      try {
        const certDir = path.join(process.cwd(), 'certs/alipay');
        return fs.readFileSync(
          path.join(certDir, 'alipayPublicKey.pem'),
          'ascii',
        );
      } catch (error) {
        console.error('读取支付宝公钥失败:', error.message);
        return process.env.ALIPAY_PUBLIC_KEY || '';
      }
    })(),

    // 网关地址
    gateway:
      process.env.ALIPAY_GATEWAY || 'https://openapi.alipay.com/gateway.do',

    // 回调地址
    notifyUrl: isDev
      ? process.env.ALIPAY_NOTIFY_URL_DEV ||
        'http://7f4c2d6f.r39.cpolar.top/api/payment/alipay/notify'
      : process.env.ALIPAY_NOTIFY_URL ||
        'https://www.diamaxiaoku.com/api/payment/alipay/notify',

    returnUrl: process.env.ALIPAY_RETURN_URL,

    // 签名类型
    signType: 'RSA2',
  };

  // --- 微信支付配置 ---
  const wechatConfig = {
    // 应用ID（公众号/小程序）
    appId: process.env.WECHAT_APP_ID || 'wxe9d6a19d79282c9b',

    // 商户号
    mchId: process.env.WECHAT_MCH_ID || '1715657600',

    // 商户API证书序列号
    serialNo:
      process.env.WECHAT_SERIAL_NO ||
      '3278C6B0F817892B0EB2A9496BEC4B14352AC6DD',

    // API v3密钥
    apiV3Key:
      process.env.WECHAT_API_V3_KEY || 'k4iBbH2ehGer0yngDNdCR6ifrNEv4uzF',

    // 证书读取
    privateKey: (() => {
      try {
        const certDir = path.join(process.cwd(), 'certs');
        const keyPath = path.join(certDir, 'wxapiclient_key.pem');

        if (!fs.existsSync(keyPath)) {
          throw new Error('私钥文件 wxapiclient_key.pem 缺失！');
        }

        return fs.readFileSync(keyPath);
      } catch (error) {
        console.error('读取微信私钥失败:', error.message);
        return Buffer.from(process.env.WECHAT_PRIVATE_KEY || '', 'utf-8');
      }
    })(),

    // 公钥
    publicKey: (() => {
      try {
        const certDir = path.join(process.cwd(), 'certs');
        const keyPath = path.join(certDir, 'pub_key.pem');

        if (!fs.existsSync(keyPath)) {
          throw new Error('公钥文件 pub_key.pem 缺失！');
        }

        return fs.readFileSync(keyPath);
      } catch (error) {
        console.error('读取微信公钥失败:', error.message);
        return Buffer.from(process.env.WECHAT_PUBLIC_KEY || '', 'utf-8');
      }
    })(),

    // 回调地址
    notifyUrl: isDev
      ? process.env.WECHAT_NOTIFY_URL_DEV ||
        'http://localhost:3001/api/payment/wechat/notify'
      : process.env.WECHAT_NOTIFY_URL ||
        'https://diamaxiaoku.com/api/payment/wechat/notify',
  };

  // 安全检查
  if (!alipayConfig.privateKey) {
    console.error('警告: 支付宝私钥未配置！');
  }
  if (!alipayConfig.alipayPublicKey) {
    console.error('警告: 支付宝公钥未配置！');
  }
  if (!wechatConfig.privateKey) {
    console.error('警告: 微信支付私钥未配置！');
  }
  if (!wechatConfig.publicKey) {
    console.error('警告: 微信支付公钥未配置！');
  }

  return {
    alipay: alipayConfig,
    wechat: wechatConfig,
  };
});




